package com.kgc.easyshopping.service.Impl;

import com.jcraft.jsch.SftpException;
import com.kgc.easyshopping.service.FileService;
import com.kgc.easyshopping.util.SftpUtil;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;


import java.util.Objects;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    private Logger log=LoggerFactory.getLogger(FileServiceImpl.class);
    @Autowired
    private SftpUtil sftpUtil;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String uploadFile(MultipartFile file) {
        if(Objects.isNull(file)){
            return "";
        }
        String originalFilename = file.getOriginalFilename();//取出文件名
        //后缀
        String hz= FilenameUtils.getExtension(originalFilename);

        String newFileName = UUID.randomUUID().toString()+"."+hz;

        //写入
        try {
            //登录
            sftpUtil.login();
            sftpUtil.sftpWriter(file,newFileName);
            sftpUtil.logout();
        } catch (Exception e) {
            log.error("上传图片文件出错：{}",e.getMessage());
        }
        //写入数据库


        return newFileName;
    }
}
